<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>音频可视化</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
            background-color: #fafafa;
        }

        h1 {
            margin-top: 50px;
        }

        #fileInput {
            margin-top: 30px;
            margin-bottom: 30px;
        }

        canvas {
            display: block;
            margin: auto;
            border: 1px solid #ddd;
            margin-top: 30px;
        }
    </style>
</head>
<body>
<h1>音频可视化</h1>
<input type="file" id="fileInput">
<canvas id="canvas"></canvas>

<script>
    const fileInput = document.getElementById('fileInput');
    fileInput.addEventListener('change', () => {
        const file = fileInput.files[0];
        const url = URL.createObjectURL(file);

        const audio = new Audio(url);
        audio.addEventListener('error', () => {
            alert('播放失败，请选择其他文件');
        });
        audio.addEventListener('canplay', () => {
            const context = new AudioContext();
            const analyzer = context.createAnalyser();
            analyzer.fftSize = 2048;

            const source = context.createMediaElementSource(audio);
            source.connect(analyzer);
            analyzer.connect(context.destination);

            const canvas = document.getElementById('canvas');
            const canvasCtx = canvas.getContext('2d');
            const width = canvas.width;
            const height = canvas.height;

            function draw() {
                requestAnimationFrame(draw);

                const bufferLength = analyzer.frequencyBinCount;
                const dataArray = new Uint8Array(bufferLength);
                analyzer.getByteFrequencyData(dataArray);

                canvasCtx.fillStyle = '#fff';
                canvasCtx.fillRect(0, 0, width, height);

                const barWidth = (width / bufferLength) * 2.5;
                let x = 0;
                for (let i = 0; i < bufferLength; i++) {
                    const barHeight = dataArray[i];

                    canvasCtx.fillStyle = 'rgb(' + (barHeight + 100) + ',50,50)';
                    canvasCtx.fillRect(x, height - barHeight / 2, barWidth, barHeight / 2);

                    x += barWidth + 1;
                }
            }

            audio.play();
            draw();
        });
    });
</script>
</body>
</html>
